---
category: Number
contributors:
    - r-i-c-h
created: '2020-05-05'
title: Clamp a number between two values
updated: '2021-10-13'
---

**JavaScript version**

```js clamp.js
const clamp = (val, min = 0, max = 1) => Math.max(min, Math.min(max, val));
```

**TypeScript version**

```ts clamp.ts
const clamp = (val: number, min: number = 0, max: number = 1): number => Math.max(min, Math.min(max, val));
```

**Examples**

```js examples.js
clamp(199, 10, 25); // 25
```

## See also

-   [Build a spin input](https://phuoc.ng/collection/html-dom/build-a-spin-input/)
-   [Wrap a number between two values](https://phuoc.ng/collection/1-loc/wrap-a-number-between-two-values/)
